import { useCallback, useEffect, useState } from 'react';
import { Image, View, StyleSheet, Text } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { router, useFocusEffect } from 'expo-router';
import axios from 'axios';
import { Button, Toast } from '@ant-design/react-native';

const picker = () => {

    const [image, setImage] = useState<string | null>(null);

    useFocusEffect(
        useCallback(() => {
            pickImage();
        }, []) // 依赖数组为空，确保只在组件挂载时运行一次
    );

    const pickImage = async () => {
        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.All,
            allowsEditing: true,
            aspect: [4, 3],
            quality: 1,
        });

        console.log(result);

        if (!result.canceled) {
            //裁剪后的图片路径
            setImage(result.assets[0].uri);
            // console.log(result.assets[0].uri);

            try {
                const info = JSON.parse(await AsyncStorage.getItem('userInfo') || '{}');
                console.log('shuju', info);

                await AsyncStorage.setItem('userInfo', JSON.stringify({ ...info, image: result.assets[0].uri }));
                let obj = {
                    _id: info._id,
                    image: result.assets[0].uri
                }
                await axios.post('http://192.168.100.31:3000/hw/EditInfo', obj).then(res => {
                    if (res.data.code == 200) {
                        Toast.success('头像修改成功')
                    }
                })
                router.back()
            }
            catch (error) {
                console.error('Error saving user info:', error);
            }

        }
    };

    return (
        <View style={styles.container}>
            {/* <Button title="打开相册" onPress={pickImage} /> */}
            {image && <Image source={{ uri: image }} style={styles.image} />}
            <Button type='primary' onPress={() => { router.back() }}>保存</Button>
        </View>
    )
}

export default picker

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    image: {
        width: 300,
        height: 600,
    },
});